package com.example.guet_assistant.handler;

import com.example.guet_assistant.pojo.entity.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;

@Service
public class MyWebSocketHandler extends TextWebSocketHandler {

    // 保存所有的 WebSocketSession 会话
    private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();

    // 用于对象序列化为 JSON
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 新的连接加入
        sessions.add(session);
        System.out.println("新连接加入: sessionId=" + session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        // 连接关闭时移除会话
        sessions.remove(session);
        System.out.println("连接关闭: sessionId=" + session.getId());
    }

    // 自定义方法：从后端主动发送对象
    public void sendObjectToAll(Message message) {
        try {

            // 将对象转换为 JSON 字符串
            String jsonMessage = objectMapper.writeValueAsString(message);


            // 遍历所有连接的会话并发送消息
            for (WebSocketSession session : sessions) {
                if (session.isOpen()) {
                    session.sendMessage(new TextMessage(jsonMessage));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
